<!-- 聊天组件 -->
<!-- Socket.IO库 -->
<script src="https://cdn.socket.io/4.5.0/socket.io.min.js"></script>

<style>
/* 悬浮按钮悬停效果 */
#chatButton:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(30, 159, 255, 0.4);
}

/* 响应式设计 */
@media (max-width: 768px) {
    #chatWindow {
        width: 300px !important;
        height: 350px !important;
        right: 10px !important;
        bottom: 10px !important;
    }
    
    #chatButton {
        width: 100px !important;
        height: 45px !important;
        right: 10px !important;
        bottom: 10px !important;
    }
    
    #chatButton span {
        font-size: 12px !important;
    }
}

/* 消息容器样式 */
#chatMessages {
    scrollbar-width: thin;
    scrollbar-color: #c1c1c1 #f1f1f1;
}

#chatMessages::-webkit-scrollbar {
    width: 6px;
}

#chatMessages::-webkit-scrollbar-track {
    background: #f1f1f1;
}

#chatMessages::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

#chatMessages::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 工具栏按钮样式 */
.toolbar-btn {
    background: none !important;
    border: none !important;
    font-size: 18px !important;
    color: #666 !important;
    cursor: pointer !important;
    padding: 8px !important;
    border-radius: 4px !important;
    transition: all 0.3s !important;
    flex-shrink: 0 !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    min-width: 36px !important;
    min-height: 36px !important;
}

.toolbar-btn:hover {
    color: #1E9FFF !important;
    background: rgba(30, 159, 255, 0.1) !important;
}

/* 表情面板样式 */
#emojiPanel {
    position: absolute !important;
    bottom: 100% !important;
    left: 0 !important;
    background: white !important;
    border: 2px solid #1E9FFF !important;
    border-radius: 8px !important;
    box-shadow: 0 8px 32px rgba(0,0,0,0.2) !important;
    padding: 15px !important;
    z-index: 9999 !important;
    width: 320px !important;
    max-height: 300px !important;
    overflow: hidden !important;
    margin-bottom: 10px !important;
}

.emoji-item {
    width: 30px !important;
    height: 30px !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    cursor: pointer !important;
    border-radius: 4px !important;
    font-size: 18px !important;
    transition: background 0.2s !important;
    user-select: none !important;
    border: 1px solid transparent !important;
}

.emoji-item:hover {
    background: #f0f0f0 !important;
    border-color: #e0e0e0 !important;
}
</style>
<div id="chatWidget" style="position: fixed; bottom: 20px; right: 20px; z-index: 9999;">
    <!-- 悬浮咨询按钮 -->
    <div id="chatButton" onclick="toggleChat()" style="
        width: 120px; 
        height: 50px; 
        background: #1E9FFF; 
        border: none; 
        border-radius: 25px; 
        color: white; 
        font-size: 14px; 
        font-weight: 500; 
        cursor: pointer; 
        display: flex; 
        align-items: center; 
        justify-content: center; 
        gap: 8px; 
        box-shadow: 0 4px 16px rgba(30, 159, 255, 0.3);
        transition: all 0.3s ease;
        z-index: 999;
    ">
        <div style="
            width: 32px; 
            height: 32px; 
            border-radius: 50%; 
            background: white; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            font-size: 16px; 
            color: #1E9FFF;
        ">
            💬
        </div>
        <span style="font-size: 14px; font-weight: 500;">在线咨询</span>
        <!-- 连接状态指示器 -->
        <div id="connectionStatus" style="
            position: absolute; 
            top: -2px; 
            right: -2px; 
            width: 12px; 
            height: 12px; 
            border-radius: 50%; 
            background: red;
            border: 2px solid white;
        "></div>
    </div>
    
    <!-- 聊天窗口 -->
    <div id="chatWindow" style="
        position: absolute; 
        bottom: 70px; 
        right: 0; 
        width: 500px;
        height: 550px;
        background: white; 
        border-radius: 12px; 
        box-shadow: 0 8px 32px rgba(0,0,0,0.1); 
        display: none; 
        flex-direction: column;
        overflow: hidden;
        z-index: 1000;
    ">
        <!-- 聊天头部 -->
        <div style="
            background: #1E9FFF; 
            color: white; 
            padding: 15px 20px; 
            display: flex; 
            align-items: center; 
            justify-content: space-between; 
            border-radius: 12px 12px 0 0;
        ">
            <div style="display: flex; align-items: center; gap: 10px;">
                <div style="
                    width: 40px; 
                    height: 40px; 
                    border-radius: 50%; 
                    background: #fff; 
                    display: flex; 
                    align-items: center; 
                    justify-content: center; 
                    font-size: 20px; 
                    color: #1E9FFF;
                ">
                    💬
                </div>
                <div>
                    <div style="font-size: 16px; font-weight: 600; margin-bottom: 2px;">在线客服</div>
                    <div id="connectionInfo" style="font-size: 12px; opacity: 0.8;">正在连接...</div>
                </div>
            </div>
            <div style="display: flex; gap: 8px;">
                <!-- 语音通话按钮 -->
                <button id="voiceCallBtn" onclick="initiateVoiceCall()" style="
                    background: none; 
                    border: 1px solid rgba(255,255,255,0.3); 
                    color: white; 
                    font-size: 14px; 
                    cursor: pointer; 
                    padding: 6px 12px; 
                    border-radius: 20px; 
                    transition: all 0.3s;
                    display: flex;
                    align-items: center;
                    gap: 4px;
                " onmouseover="this.style.background='rgba(255,255,255,0.2)'; this.style.borderColor='rgba(255,255,255,0.6)'" onmouseout="this.style.background='none'; this.style.borderColor='rgba(255,255,255,0.3)'">
                    <span style="font-size: 16px;">📞</span>
                    <span id="callBtnText">语音</span>
                </button>
                
                <!-- 视频通话按钮 -->
                <button id="videoCallBtn" onclick="initiateVideoCall()" style="
                    background: none; 
                    border: 1px solid rgba(255,255,255,0.3); 
                    color: white; 
                    font-size: 14px; 
                    cursor: pointer; 
                    padding: 6px 12px; 
                    border-radius: 20px; 
                    transition: all 0.3s;
                    display: flex;
                    align-items: center;
                    gap: 4px;
                " onmouseover="this.style.background='rgba(255,255,255,0.2)'; this.style.borderColor='rgba(255,255,255,0.6)'" onmouseout="this.style.background='none'; this.style.borderColor='rgba(255,255,255,0.3)'">
                    <span style="font-size: 16px;">📹</span>
                    <span id="videoCallBtnText">视频</span>
                </button>
                
                <!-- 桌面共享按钮 -->
                <button id="desktopShareBtn" onclick="initiateDesktopShare()" style="
                    background: none; 
                    border: 1px solid rgba(255,255,255,0.3); 
                    color: white; 
                    font-size: 14px; 
                    cursor: pointer; 
                    padding: 6px 12px; 
                    border-radius: 20px; 
                    transition: all 0.3s;
                    display: flex;
                    align-items: center;
                    gap: 4px;
                " onmouseover="this.style.background='rgba(255,255,255,0.2)'; this.style.borderColor='rgba(255,255,255,0.6)'" onmouseout="this.style.background='none'; this.style.borderColor='rgba(255,255,255,0.3)'">
                    <span style="font-size: 16px;">🖥️</span>
                    <span id="desktopShareBtnText">桌面共享</span>
                </button>
                
                <button onclick="toggleChat()" style="
                    background: none; 
                    border: none; 
                    color: white; 
                    font-size: 16px; 
                    cursor: pointer; 
                    padding: 4px; 
                    border-radius: 4px; 
                    transition: background 0.3s;
                " onmouseover="this.style.background='rgba(255,255,255,0.2)'" onmouseout="this.style.background='none'">
                    <i class="layui-icon layui-icon-minus"></i>
                </button>
                <button onclick="toggleChat()" style="
                    background: none; 
                    border: none; 
                    color: white; 
                    font-size: 16px; 
                    cursor: pointer; 
                    padding: 4px; 
                    border-radius: 4px; 
                    transition: background 0.3s;
                " onmouseover="this.style.background='rgba(255,255,255,0.2)'" onmouseout="this.style.background='none'">
                    <i class="layui-icon layui-icon-close"></i>
                </button>
            </div>
        </div>
        
        <!-- 聊天消息区域 -->
        <div id="chatMessages" style="
            flex: 1; 
            padding: 20px; 
            overflow-y: auto; 
            background: #f8f9fa;
        ">
            <!-- 消息将在这里显示 -->
        </div>
        
        <!-- 输入区域 -->
        <div style="padding: 15px 20px; background: white; border-top: 1px solid #e0e0e0;">
            <div style="display: flex; flex-direction: column; gap: 10px;">
                <!-- 用户信息输入 -->
                <div id="userInfoPanel" style="display: none;">
                    <input type="text" id="userName" placeholder="您的姓名" style="
                        width: 100%; 
                        padding: 8px 12px; 
                        border: 1px solid #e0e0e0; 
                        border-radius: 20px; 
                        margin-bottom: 8px;
                        outline: none;
                        transition: border-color 0.3s;
                    " onfocus="this.style.borderColor='#1E9FFF'" onblur="this.style.borderColor='#e0e0e0'">
                    <input type="text" id="userPhone" placeholder="您的电话" style="
                        width: 100%; 
                        padding: 8px 12px; 
                        border: 1px solid #e0e0e0; 
                        border-radius: 20px;
                        outline: none;
                        transition: border-color 0.3s;
                    " onfocus="this.style.borderColor='#1E9FFF'" onblur="this.style.borderColor='#e0e0e0'">
                </div>
                
                <!-- 工具栏和电话区域 -->
                <div style="display: flex; gap: 8px; align-items: center;">
                    <div style="display: flex; gap: 8px; align-items: center; position: relative;">
                        <!-- 表情按钮 -->
                        <button onclick="toggleEmoji()" class="toolbar-btn" title="表情">
                            😊
                        </button>
                        
                        <!-- 表情面板 -->
                        <div id="emojiPanel" style="
                            position: absolute; 
                            bottom: 100%; 
                            left: 0; 
                            background: white; 
                            border: 2px solid #1E9FFF; 
                            border-radius: 8px; 
                            box-shadow: 0 8px 32px rgba(0,0,0,0.2); 
                            padding: 15px; 
                            display: none; 
                            z-index: 9999; 
                            width: 320px; 
                            max-height: 300px; 
                            overflow: hidden;
                            margin-bottom: 10px;
                        ">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; border-bottom: 1px solid #e0e0e0; padding-bottom: 10px;">
                                <div style="font-size: 14px; font-weight: 600; color: #333;">选择表情</div>
                                <button onclick="toggleEmoji()" style="background: none; border: none; font-size: 18px; cursor: pointer; color: #666;">✕</button>
                            </div>
                            <div style="margin-bottom: 15px;">
                                <div style="font-size: 12px; color: #666; margin-bottom: 8px; padding: 0 5px;">常用表情</div>
                                <div style="display: grid; grid-template-columns: repeat(8, 1fr); gap: 10px;">
                                    <div onclick="insertEmoji('😊')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">😊</div>
                                    <div onclick="insertEmoji('😂')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">😂</div>
                                    <div onclick="insertEmoji('😍')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">😍</div>
                                    <div onclick="insertEmoji('🤔')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">🤔</div>
                                    <div onclick="insertEmoji('👍')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">👍</div>
                                    <div onclick="insertEmoji('👎')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">👎</div>
                                    <div onclick="insertEmoji('❤️')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">❤️</div>
                                    <div onclick="insertEmoji('😭')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">😭</div>
                                    <div onclick="insertEmoji('😡')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">😡</div>
                                    <div onclick="insertEmoji('😱')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">😱</div>
                                    <div onclick="insertEmoji('🎉')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">🎉</div>
                                    <div onclick="insertEmoji('💯')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">💯</div>
                                    <div onclick="insertEmoji('🔥')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">🔥</div>
                                    <div onclick="insertEmoji('✨')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">✨</div>
                                    <div onclick="insertEmoji('💪')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">💪</div>
                                    <div onclick="insertEmoji('🙏')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">🙏</div>
                                </div>
                            </div>
                            <div style="margin-bottom: 15px;">
                                <div style="font-size: 12px; color: #666; margin-bottom: 8px; padding: 0 5px;">手势表情</div>
                                <div style="display: grid; grid-template-columns: repeat(8, 1fr); gap: 10px;">
                                    <div onclick="insertEmoji('👋')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">👋</div>
                                    <div onclick="insertEmoji('✌️')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">✌️</div>
                                    <div onclick="insertEmoji('🤝')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">🤝</div>
                                    <div onclick="insertEmoji('👏')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">👏</div>
                                    <div onclick="insertEmoji('🙌')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">🙌</div>
                                    <div onclick="insertEmoji('🤗')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">🤗</div>
                                    <div onclick="insertEmoji('💁')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">💁</div>
                                    <div onclick="insertEmoji('🤷')" style="width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; cursor: pointer; border-radius: 6px; font-size: 20px; transition: all 0.2s; user-select: none; border: 1px solid transparent;" onmouseover="this.style.background='#f0f0f0'; this.style.borderColor='#1E9FFF'; this.style.transform='scale(1.1)'" onmouseout="this.style.background='transparent'; this.style.borderColor='transparent'; this.style.transform='scale(1)'">🤷</div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 图片上传按钮 -->
                        <button onclick="uploadImage()" class="toolbar-btn" title="图片">
                            📷
                        </button>
                        
                        <!-- 隐藏的文件输入框 -->
                        <input type="file" id="imageInput" accept="image/*" style="display: none;">
                        
                        <!-- 文件上传按钮 -->
                        <button onclick="uploadFile()" class="toolbar-btn" title="文件">
                            📁
                        </button>
                        
                        <!-- 语音按钮 -->
                        <button onclick="startVoice()" class="toolbar-btn" title="语音">
                            🎤
                        </button>
                    </div>
                    
                    <!-- 电话区域 -->
                    <div style="display: none; gap: 8px; align-items: center; margin-left: auto;">
                        <input type="tel" id="phoneInput" placeholder="输入电话号码" style="
                            border: 1px solid #e0e0e0;
                            border-radius: 20px;
                            padding: 8px 12px;
                            font-size: 14px;
                            outline: none;
                            transition: border-color 0.3s;
                            width: 120px;
                        " onfocus="this.style.borderColor='#1E9FFF'" onblur="this.style.borderColor='#e0e0e0'">
                        <button onclick="makeCall()" style="
                            background: #52c41a;
                            color: white;
                            border: none;
                            padding: 8px 12px;
                            border-radius: 20px;
                            cursor: pointer;
                            font-size: 14px;
                            transition: background 0.3s;
                            white-space: nowrap;
                            flex-shrink: 0;
                        " onmouseover="this.style.background='#389e0d'" onmouseout="this.style.background='#52c41a'">
                            电话联系
                        </button>
                    </div>
                </div>

                <!-- 消息输入区域 -->
                <div style="display: flex; gap: 8px; align-items: flex-end; position: relative;">
                    <textarea id="messageInput" placeholder="输入消息内容..." style="
                        flex: 1; 
                        border: 1px solid #e0e0e0; 
                        border-radius: 20px; 
                        padding: 12px 15px; 
                        padding-right: 70px; 
                        font-size: 14px; 
                        resize: none; 
                        outline: none; 
                        transition: border-color 0.3s; 
                        height: 60px; 
                        overflow-y: auto;
                    " onfocus="this.style.borderColor='#1E9FFF'" onblur="this.style.borderColor='#e0e0e0'" onkeypress="handleKeyPress(event)"></textarea>
                    <button id="sendButton" onclick="sendMessage()" style="
                        background: #1E9FFF; 
                        color: white; 
                        border: none; 
                        padding: 10px 18px; 
                        border-radius: 20px; 
                        cursor: pointer; 
                        font-size: 14px; 
                        transition: background 0.3s; 
                        white-space: nowrap; 
                        position: absolute; 
                        bottom: 10px; 
                        right: 10px; 
                        z-index: 10;
                    " onmouseover="this.style.background='#0d8aff'" onmouseout="this.style.background='#1E9FFF'" disabled>发送</button>
                </div>
            </div>
            
            <!-- Debug信息 -->
            <div id="debugInfo" style="
                font-size: 11px; 
                color: #666; 
                margin-top: 5px; 
                display: none;
            "></div>
        </div>
        
        <!-- 底部信息 -->
        <div style="padding: 8px 20px; background: #f8f9fa; text-align: center; font-size: 11px; color: #999; border-top: 1px solid #e0e0e0;">
            PPress提供咨询软件支持
        </div>
    </div>
</div>

<script>
let chatVisible = false;
let socket = null;
let chatSessionId = null;
let userInfo = {
    name: '',
    phone: ''
};
let userHasInteracted = false; // 用户是否已经与页面交互过
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;

// 语音通话功能变量
let localStream = null;
let remoteStream = null;
let peerConnection = null;
let isCallActive = false;
let callStartTime = null;
let callTimer = null;
let remoteAudio = null; // 远程音频播放元素
let iceCandidateQueue = []; // ICE候选队列
let callTimeoutTimer = null; // 呼叫超时定时器
let currentCallState = 'idle'; // idle, calling, ringing, connected

// 视频通话功能变量
let videoLocalStream = null;
let videoRemoteStream = null;
let videoPeerConnection = null;
let isVideoCallActive = false;
let videoCallStartTime = null;
let videoCallTimer = null;
let remoteVideo = null; // 远程视频播放元素
let localVideo = null; // 本地视频播放元素
let videoIceCandidateQueue = []; // 视频ICE候选队列
let videoCallTimeoutTimer = null; // 视频呼叫超时定时器
let currentVideoCallState = 'idle'; // idle, calling, ringing, connected
let isVideoCall = false; // 区分语音通话和视频通话

// 桌面共享相关变量
let desktopShareStream = null; // 桌面共享流
let desktopSharePeerConnection = null; // 桌面共享WebRTC连接
let isDesktopSharing = false; // 是否正在桌面共享
let desktopShareStartTime = null; // 桌面共享开始时间
let desktopShareTimer = null; // 桌面共享计时器
let desktopShareTimeoutTimer = null; // 桌面共享超时定时器
let currentDesktopShareState = 'idle'; // 桌面共享状态
let desktopShareIceCandidateQueue = []; // 桌面共享ICE候选队列

// WebRTC配置
const rtcConfig = {
    iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
        { urls: 'stun:stun1.l.google.com:19302' }
    ]
};

// 初始化远程音频元素
function initRemoteAudio() {
    if (!remoteAudio) {
        remoteAudio = document.createElement('audio');
        remoteAudio.autoplay = true;
        remoteAudio.playsInline = true;
        document.body.appendChild(remoteAudio);
        console.log('用户远程音频元素已创建');
    }
}

// 初始化视频元素
function initVideoElements() {
    // 创建本地视频元素
    if (!localVideo) {
        localVideo = document.createElement('video');
        localVideo.autoplay = true;
        localVideo.playsInline = true;
        localVideo.muted = true; // 本地视频静音避免回声
        localVideo.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            width: 200px;
            height: 150px;
            border: 2px solid #1E9FFF;
            border-radius: 8px;
            background: #000;
            z-index: 1000;
        `;
        document.body.appendChild(localVideo);
        console.log('用户本地视频元素已创建');
    }
    
    // 创建远程视频元素
    if (!remoteVideo) {
        remoteVideo = document.createElement('video');
        remoteVideo.autoplay = true;
        remoteVideo.playsInline = true;
        remoteVideo.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 80vw;
            height: 60vh;
            border: 2px solid #28a745;
            border-radius: 8px;
            background: #000;
            z-index: 1000;
        `;
        document.body.appendChild(remoteVideo);
        console.log('用户远程视频元素已创建');
    }
}

// 获取用户视频设备
async function getUserVideo() {
    try {
        console.log('正在获取用户摄像头权限...');
        
        videoLocalStream = await navigator.mediaDevices.getUserMedia({
            audio: {
                echoCancellation: true,
                noiseSuppression: true,
                autoGainControl: true
            },
            video: {
                width: { ideal: 1280 },
                height: { ideal: 720 },
                frameRate: { ideal: 30 }
            }
        });
        
        console.log('摄像头权限获取成功');
        return videoLocalStream;
    } catch (error) {
        console.error('获取摄像头失败:', error);
        throw error;
    }
}

// 创建视频WebRTC连接
async function createVideoPeerConnection() {
    try {
        console.log('创建视频WebRTC连接...');
        
        videoPeerConnection = new RTCPeerConnection(rtcConfig);
        
        // 添加本地音视频流
        if (videoLocalStream) {
            const tracks = videoLocalStream.getTracks();
            tracks.forEach(track => {
                videoPeerConnection.addTrack(track, videoLocalStream);
                console.log('本地音视频轨道已添加:', track.kind);
            });
        }
        
        // 处理远程音视频流
        videoPeerConnection.ontrack = (event) => {
            console.log('收到远程音视频流');
            videoRemoteStream = event.streams[0];
            
            if (remoteVideo) {
                remoteVideo.srcObject = videoRemoteStream;
                remoteVideo.play().catch(e => console.error('播放远程视频失败:', e));
            }
        };
        
        // 处理ICE候选
        videoPeerConnection.onicecandidate = (event) => {
            if (event.candidate) {
                console.log('发送视频ICE候选:', event.candidate);
                socket.emit('video_ice_candidate', {
                    session_id: chatSessionId,
                    candidate: event.candidate,
                    sender: 'user'
                });
            }
        };
        
        // 监控连接状态
        videoPeerConnection.onconnectionstatechange = () => {
            console.log('视频WebRTC连接状态:', videoPeerConnection.connectionState);
            if (videoPeerConnection.connectionState === 'connected') {
                console.log('视频WebRTC连接已建立');
                startVideoCall();
            } else if (videoPeerConnection.connectionState === 'failed' || 
                       videoPeerConnection.connectionState === 'disconnected') {
                console.log('视频WebRTC连接失败或断开');
                endVideoCall();
            }
        };
        
        console.log('视频WebRTC连接创建成功');
        return videoPeerConnection;
    } catch (error) {
        console.error('创建视频WebRTC连接失败:', error);
        throw error;
    }
}

// 处理管理员的视频WebRTC Offer
async function handleAdminVideoOffer(offer) {
    try {
        console.log('处理管理员的视频WebRTC Offer');
        
        // 获取摄像头权限
        await getUserVideo();
        
        // 初始化视频元素
        initVideoElements();
        
        // 显示本地视频
        if (localVideo && videoLocalStream) {
            localVideo.srcObject = videoLocalStream;
        }
        
        // 创建连接
        await createVideoPeerConnection();
        
        // 设置远程描述
        await videoPeerConnection.setRemoteDescription(offer);
        console.log('视频远程描述设置成功');
        
        // 处理队列中的ICE候选
        while (videoIceCandidateQueue.length > 0) {
            const candidate = videoIceCandidateQueue.shift();
            try {
                await videoPeerConnection.addIceCandidate(new RTCIceCandidate(candidate));
                console.log('队列视频ICE候选添加成功');
            } catch (error) {
                console.error('队列视频ICE候选添加失败:', error);
            }
        }
        
        // 创建应答
        const answer = await videoPeerConnection.createAnswer();
        await videoPeerConnection.setLocalDescription(answer);
        
        // 发送应答给管理员
        socket.emit('video_call_answer', {
            session_id: chatSessionId,
            answer: answer
        });
        
        console.log('视频WebRTC应答已发送');
        
    } catch (error) {
        console.error('处理管理员视频Offer失败:', error);
        addSystemMessage('建立视频连接失败');
        endVideoCall();
    }
}

// 语音通话按钮状态更新
function updateCallButton(state, text) {
    const callBtn = document.getElementById('voiceCallBtn');
    const callBtnText = document.getElementById('callBtnText');
    
    if (!callBtn || !callBtnText) return;
    
    switch (state) {
        case 'idle':
            callBtn.style.background = 'none';
            callBtn.style.borderColor = 'rgba(255,255,255,0.3)';
            callBtnText.textContent = '语音';
            callBtn.onclick = initiateVoiceCall;
            break;
        case 'calling':
            callBtn.style.background = 'rgba(255,193,7,0.8)';
            callBtn.style.borderColor = '#ffc107';
            callBtnText.textContent = '呼叫中...';
            callBtn.onclick = cancelVoiceCall;
            break;
        case 'connected':
            callBtn.style.background = 'rgba(220,53,69,0.8)';
            callBtn.style.borderColor = '#dc3545';
            callBtnText.textContent = text || '结束通话';
            callBtn.onclick = endVoiceCall;
            break;
        case 'ringing':
            callBtn.style.background = 'rgba(23,162,184,0.8)';
            callBtn.style.borderColor = '#17a2b8';
            callBtnText.textContent = '来电中...';
            callBtn.onclick = answerVoiceCall;
            break;
        case 'queued':
            callBtn.style.background = 'rgba(255,193,7,0.8)';
            callBtn.style.borderColor = '#ffc107';
            callBtnText.textContent = '排队中...';
            callBtn.onclick = cancelVoiceCall;
            break;
        case 'connecting':
            callBtn.style.background = 'rgba(32,201,151,0.8)';
            callBtn.style.borderColor = '#20c997';
            callBtnText.textContent = '连接中...';
            callBtn.onclick = endVoiceCall; // Allow ending during connection
            break;
    }
}

// 视频通话按钮状态更新
function updateVideoCallButton(state, text) {
    const videoCallBtn = document.getElementById('videoCallBtn');
    const videoCallBtnText = document.getElementById('videoCallBtnText');
    
    if (!videoCallBtn || !videoCallBtnText) return;
    
    switch (state) {
        case 'idle':
            videoCallBtn.style.background = 'none';
            videoCallBtn.style.borderColor = 'rgba(255,255,255,0.3)';
            videoCallBtnText.textContent = '视频';
            videoCallBtn.onclick = initiateVideoCall;
            break;
        case 'calling':
            videoCallBtn.style.background = 'rgba(255,193,7,0.8)';
            videoCallBtn.style.borderColor = '#ffc107';
            videoCallBtnText.textContent = '呼叫中...';
            videoCallBtn.onclick = cancelVideoCall;
            break;
        case 'ringing':
            videoCallBtn.style.background = 'rgba(40,167,69,0.8)';
            videoCallBtn.style.borderColor = '#28a745';
            videoCallBtnText.textContent = '接听';
            videoCallBtn.onclick = answerVideoCall;
            break;
        case 'connected':
            videoCallBtn.style.background = 'rgba(220,53,69,0.8)';
            videoCallBtn.style.borderColor = '#dc3545';
            videoCallBtnText.textContent = text || '结束通话';
            videoCallBtn.onclick = endVideoCall;
            break;
        case 'queued':
            videoCallBtn.style.background = 'rgba(255,193,7,0.8)';
            videoCallBtn.style.borderColor = '#ffc107';
            videoCallBtnText.textContent = '排队中...';
            videoCallBtn.onclick = cancelVideoCall;
            break;
        case 'connecting':
            videoCallBtn.style.background = 'rgba(32,201,151,0.8)';
            videoCallBtn.style.borderColor = '#20c997';
            videoCallBtnText.textContent = '连接中...';
            videoCallBtn.onclick = endVideoCall; // Allow ending during connection
            break;
    }
}

// 发起语音通话
function initiateVoiceCall() {
    console.log('发起语音通话');
    
    if (!socket || !socket.connected) {
        addSystemMessage('连接已断开，无法发起通话');
        return;
    }
    
    if (!chatSessionId) {
        addSystemMessage('会话未建立，无法发起通话');
        return;
    }
    
    currentCallState = 'calling';
    updateCallButton('calling');
    
    // 发送通话请求
    socket.emit('voice_call_request', {
        session_id: chatSessionId,
        user_info: {
            name: localStorage.getItem('userName') || '',
            phone: localStorage.getItem('userPhone') || ''
        }
    });
    
    addSystemMessage('正在呼叫客服，请稍候...');
    
    // 设置30秒超时
    callTimeoutTimer = setTimeout(() => {
        if (currentCallState === 'calling') {
            console.log('通话超时，无人接听');
            handleCallTimeout();
        }
    }, 30000); // 30秒超时
}

// 取消语音通话
function cancelVoiceCall() {
    console.log('取消语音通话');
    
    if (!socket || !socket.connected || !chatSessionId) {
        console.log('无效的连接状态，无法取消通话');
        return;
    }
    
    // 清理状态
    clearCallTimeout();
    cleanupCall();
    
    // 发送取消通话信号
    socket.emit('voice_call_cancel', {
        session_id: chatSessionId,
        user_info: {
            name: localStorage.getItem('userName') || '',
            phone: localStorage.getItem('userPhone') || ''
        }
    });
    
    // 添加系统消息到用户端聊天框
    addSystemMessage('您已取消语音通话');
    
    currentCallState = 'idle';
    updateCallButton('idle');
}

// 结束语音通话
function endVoiceCall() {
    console.log('结束语音通话');
    
    if (socket && socket.connected) {
        socket.emit('voice_call_end', {
            session_id: chatSessionId
        });
    }
    
    cleanupCall();
    updateCallButton('idle');
    
    if (callStartTime) {
        const duration = Math.floor((Date.now() - callStartTime) / 1000);
        const minutes = Math.floor(duration / 60);
        const seconds = duration % 60;
        addSystemMessage(`通话已结束，通话时长: ${minutes}:${seconds.toString().padStart(2, '0')}`);
    } else {
        addSystemMessage('通话已结束');
    }
}

// 接听语音通话
async function answerVoiceCall() {
    console.log('接听语音通话');
    
    try {
        // 立即停止铃声
        stopRingtone();
        console.log('用户接听，停止铃声');
        
        // 更新通话状态为已接听
        currentCallState = 'connecting';
        updateCallButton('connecting');
        
        // 发送接听确认（让管理员创建WebRTC连接）
        socket.emit('voice_call_accept', {
            session_id: chatSessionId,
            user_info: {
                name: localStorage.getItem('userName') || '',
                phone: localStorage.getItem('userPhone') || ''
            }
        });
        
        addSystemMessage('已接听通话，等待建立音频连接...');
        
    } catch (error) {
        console.error('接听通话失败:', error);
        addSystemMessage('接听通话失败');
        updateCallButton('idle');
    }
}

// 开始通话
function startCall() {
    isCallActive = true;
    callStartTime = Date.now();
    currentCallState = 'connected';
    updateCallButton('connected');
    
    // 开始计时
    callTimer = setInterval(() => {
        if (callStartTime) {
            const duration = Math.floor((Date.now() - callStartTime) / 1000);
            const minutes = Math.floor(duration / 60);
            const seconds = duration % 60;
            updateCallButton('connected', `${minutes}:${seconds.toString().padStart(2, '0')}`);
        }
    }, 1000);
    
    addSystemMessage('语音通话已连接');
}

// 清理通话资源
function cleanupCall() {
    isCallActive = false;
    callStartTime = null;
    
    if (callTimer) {
        clearInterval(callTimer);
        callTimer = null;
    }
    
    if (localStream) {
        localStream.getTracks().forEach(track => track.stop());
        localStream = null;
    }
    
    if (remoteStream) {
        remoteStream = null;
    }
    
    // 清理远程音频
    if (remoteAudio) {
        remoteAudio.srcObject = null;
        console.log('用户远程音频已清理');
    }
    
    if (peerConnection) {
        peerConnection.close();
        peerConnection = null;
    }
    
    // 清空ICE候选队列
    iceCandidateQueue = [];
    console.log('用户ICE候选队列已清空');
    
    // 同时清理视频通话资源
    cleanupVideoCall();
    
    console.log('用户通话资源清理完成');
}

// 从localStorage恢复数据
function restoreFromStorage() {
    const savedSessionId = getDataWithExpiration('chatSessionId');
    const savedUserInfo = getDataWithExpiration('chatUserInfo');
    console.info('从localStorage恢复数据:', savedSessionId, savedUserInfo)
    if (savedSessionId) {
        chatSessionId = savedSessionId;
    }
    
    if (savedUserInfo) {
        try {
            userInfo = JSON.parse(savedUserInfo);
            // 设置输入框的值
            const nameInput = document.getElementById('userName');
            const phoneInput = document.getElementById('userPhone');
            if (nameInput) nameInput.value = userInfo.name || '';
            if (phoneInput) phoneInput.value = userInfo.phone || '';
            
            console.log('用户信息已恢复:', userInfo);
        } catch (e) {
            console.error('恢复用户信息失败:', e);
            userInfo = {};
        }
    } else {
        userInfo = {};
    }
}

// 保存到localStorage
function saveToStorage() {
    if (chatSessionId) {
        setDataWithExpiration("chatSessionId", chatSessionId, 1)
        //localStorage.setItem('chatSessionId', chatSessionId);
    }
    console.info('保存到localStorage:', chatSessionId)
    if (userInfo.name || userInfo.phone) {
        //localStorage.setItem('chatUserInfo', JSON.stringify(userInfo));
        setDataWithExpiration("chatUserInfo", JSON.stringify(userInfo), 24)
    }
    console.info('保存用户信息到localStorage:', userInfo)
}



// 设置数据，包含一个有效期
function setDataWithExpiration(key, value, expirationHours) {
    const now = new Date();
    const item = {
        value: value,
        expiry: now.getTime() + expirationHours * 60 * 60 * 1000 // 设置过期时间（小时）
    };
    localStorage.setItem(key, JSON.stringify(item));
}

// 获取数据，检查是否过期
function getDataWithExpiration(key) {
    const itemStr = localStorage.getItem(key);
    if (!itemStr) {
        return null;
    }
    const item = JSON.parse(itemStr);
    const now = new Date();
    if (now.getTime() > item.expiry) {
        // 数据已过期，删除并返回null
        localStorage.removeItem(key);
        return null;
    }
    return item.value;
}

// 更新连接状态
function updateConnectionStatus(status) {
    const statusElement = document.getElementById('connectionStatus');
    const infoElement = document.getElementById('connectionInfo');
    const sendButton = document.getElementById('sendButton');
    const debugInfo = document.getElementById('debugInfo');
    
    switch (status) {
        case 'connected':
            statusElement.style.background = 'green';
            infoElement.textContent = '已连接';
            sendButton.disabled = false;
            break;
        case 'connecting':
            statusElement.style.background = 'yellow';
            infoElement.textContent = '正在连接...';
            sendButton.disabled = true;
            break;
        case 'disconnected':
            statusElement.style.background = 'red';
            infoElement.textContent = '连接已断开';
            sendButton.disabled = true;
            break;
        case 'error':
            statusElement.style.background = 'red';
            infoElement.textContent = '连接错误';
            sendButton.disabled = true;
            break;
    }
    
    // 显示调试信息
    debugInfo.textContent = `状态: ${status}, 重连次数: ${reconnectAttempts}`;
    debugInfo.style.display = 'block';
}

// 初始化WebSocket连接
function initSocket() {
    try {
        updateConnectionStatus('connecting');
        
        socket = io('/chat', {
            transports: ['polling', 'websocket'],
            timeout: 20000,
            reconnection: true,
            reconnectionAttempts: maxReconnectAttempts,
            reconnectionDelay: 1000,
            reconnectionDelayMax: 5000,
            forceNew: true,
            secure: false
        });
        
        // 连接成功
        socket.on('connect', function() {
            console.log('WebSocket连接成功');
            updateConnectionStatus('connected');
            reconnectAttempts = 0;
            
            // 发送测试连接请求
            socket.emit('test_connection');
        });
        
        // 测试连接响应
        socket.on('test_response', function(data) {
            console.log('收到测试响应:', data);
            addSystemMessage(data.msg);
            
            // 测试成功后再尝试加入聊天
            setTimeout(function() {
                if (socket && socket.connected) {
                    console.log('开始加入聊天会话');
                    joinChat();
                }
            }, 100);
        });
        
        // 连接断开
        socket.on('disconnect', function(reason) {
            console.log('WebSocket连接断开:', reason);
            updateConnectionStatus('disconnected');
            
            if (reason === 'io server disconnect') {
                // 服务器主动断开，需要手动重连
                socket.connect();
            }
        });
        
        // 连接错误
        socket.on('connect_error', function(error) {
            console.error('WebSocket连接错误:', error);
            updateConnectionStatus('error');
            
            // 显示用户友好的错误信息
            addSystemMessage('连接服务器失败，请检查网络连接');
        });
        
        // 重连尝试
        socket.on('reconnect_attempt', function(attemptNumber) {
            console.log('尝试重连:', attemptNumber);
            reconnectAttempts = attemptNumber;
            updateConnectionStatus('connecting');
        });
        
        // 重连失败
        socket.on('reconnect_failed', function() {
            console.log('重连失败');
            updateConnectionStatus('error');
            addSystemMessage('连接已断开，请刷新页面重试');
        });
        
        // 加入聊天成功
        socket.on('joined', function(data) {
            console.log('加入聊天成功:', data);
            chatSessionId = data.session_id;
            saveToStorage();
        });
        
        // 历史消息
        socket.on('history_messages', function(data) {
            console.log('收到历史消息:', data);
            const messages = data.messages || [];
            messages.forEach(function(msg) {
                // 根据消息类型显示不同内容
                if (msg.message_type === 'image' && msg.image_data) {
                    addImageMessage(msg.image_data, msg.sender_type, msg.create_time);
                } else {
                    addMessage(msg.content, msg.sender_type, msg.create_time);
                }
            });
        });
        
        // 新消息
        socket.on('new_message', function(data) {
            console.log('收到新消息:', data);
            
            // 播放提示音（只有当消息不是用户自己发送的时才播放）
            if (data.sender_type !== 'user') {
                playMessageSound();
            }
            
            // 根据消息类型显示不同内容
            if (data.message_type === 'image' && data.image_data) {
                addImageMessage(data.image_data, data.sender_type, data.create_time);
            } else {
                addMessage(data.content, data.sender_type, data.create_time);
            }
        });
        
        // 会话关闭
        socket.on('session_closed', function(data) {
            console.log('会话已关闭:', data);
            addSystemMessage(data.msg || '会话已关闭');
        });
        
        // 管理员正在输入
        socket.on('admin_typing', function(data) {
            showTypingIndicator('admin', data.msg);
        });
        
        // 管理员停止输入
        socket.on('admin_stop_typing', function() {
            hideTypingIndicator();
        });
        
        // 语音通话事件处理
        
        // 收到来电
        socket.on('voice_call_incoming', function(data) {
            console.log('收到管理员来电，data类型:', typeof data, 'data键:', Object.keys(data));
            
            clearCallTimeout(); // 清理超时定时器
            
            if (data.type === 'callback') {
                // 管理员回拨，需要用户接听
                console.log('管理员回拨，等待用户接听');
                currentCallState = 'ringing';
                updateCallButton('ringing');
                playRingtone();
                addSystemMessage('客服正在回拨您，请点击接听');
            } else if (data.offer) {
                // 管理员发送了WebRTC offer（用户接听了回拨）
                console.log('收到管理员的WebRTC offer');
                
                // 确保停止铃声和更新状态
                stopRingtone();
                currentCallState = 'connecting';
                updateCallButton('connecting');
                console.log('收到offer，停止铃声并更新状态为connecting');
                
                handleAdminOffer(data.offer);
            } else {
                // 普通来电（从排队状态转为来电状态）
                console.log('轮到您了，管理员来电');
                currentCallState = 'ringing';
                updateCallButton('ringing');
                playRingtone();
                
                // 根据之前的状态给出不同提示
                if (currentCallState === 'queued') {
                    addSystemMessage('🎉 轮到您了！客服正在呼叫您，请接听');
                } else {
                    addSystemMessage('客服正在呼叫您，请接听');
                }
            }
        });
        
        // 处理ICE候选
        socket.on('ice_candidate', function(data) {
            console.log('收到ICE候选:', data);
            if (peerConnection && data.candidate && data.sender !== 'user') {
                // 检查是否已设置远程描述
                if (peerConnection.remoteDescription) {
                    // 远程描述已设置，直接添加ICE候选
                    peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate))
                        .then(() => {
                            console.log('用户ICE候选添加成功');
                        })
                        .catch(error => {
                            console.error('用户ICE候选添加失败:', error);
                        });
                } else {
                    // 远程描述未设置，将ICE候选加入队列
                    console.log('远程描述未设置，ICE候选加入队列');
                    iceCandidateQueue.push(data.candidate);
                }
            }
        });
        
        // 通话被接听
        socket.on('voice_call_accepted', function(data) {
            console.log('通话被接听:', data);
            startCall();
        });
        
        // 通话被拒绝
        socket.on('voice_call_rejected', function(data) {
            console.log('通话被拒绝:', data);
            clearCallTimeout();
            cleanupCall();
            currentCallState = 'idle';
            updateCallButton('idle');
            addSystemMessage('客服拒绝了通话');
        });
        
        // 通话被取消
        socket.on('voice_call_cancelled', function(data) {
            console.log('通话被取消:', data);
            clearCallTimeout();
            cleanupCall();
            currentCallState = 'idle';
            updateCallButton('idle');
            addSystemMessage('通话已取消');
        });
        
        // 通话结束
        socket.on('voice_call_ended', function(data) {
            console.log('通话结束:', data);
            clearCallTimeout();
            cleanupCall();
            currentCallState = 'idle';
            updateCallButton('idle');
            addSystemMessage('通话已结束');
        });
        
        // 错误处理
        socket.on('error', function(data) {
            console.error('WebSocket错误:', data);
            addSystemMessage('错误: ' + (data.msg || '未知错误'));
        });
        
        // 语音通话队列状态更新
        socket.on('voice_call_queue_update', function(data) {
            console.log('收到队列状态更新:', data);
            
            if (data.session_id === chatSessionId) {
                // 更新通话状态为排队中
                currentCallState = 'queued';
                updateCallButton('queued');
                
                // 显示队列信息
                addSystemMessage(data.message);
                
                // 如果是第一位，给特殊提示
                if (data.position === 1) {
                    addSystemMessage('💡 您是下一位，客服处理完当前通话后将立即为您接通');
                }
                
                console.log('用户通话状态更新为排队中，位置:', data.position);
            }
        });

        // 语音通话被拒绝
        socket.on('voice_call_rejected', function(data) {
            console.log('语音通话被拒绝:', data);
            clearCallTimeout();
            cleanupCall();
            currentCallState = 'idle';
            updateCallButton('idle');
            addSystemMessage('客服拒绝了通话');
        });
        
        // 管理员回拨被取消
        socket.on('voice_call_callback_cancelled', function(data) {
            console.log('管理员取消了回拨:', data);
            
            if (data.session_id === chatSessionId) {
                // 停止铃声
                stopRingtone();
                
                // 重置状态
                currentCallState = 'idle';
                updateCallButton('idle');
                
                // 显示系统消息
                addSystemMessage('客服取消了回拨');
                
                console.log('用户端回拨状态已重置');
            }
        });
        
        // 拨号自动取消（客服不在线）
        socket.on('voice_call_auto_cancelled', function(data) {
            console.log('收到拨号自动取消通知:', data);
            
            if (data.session_id === chatSessionId) {
                // 清理通话状态
                clearCallTimeout();
                cleanupCall();
                currentCallState = 'idle';
                updateCallButton('idle');
                
                // 显示系统消息
                addSystemMessage('📞 客服不在线，拨号已自动取消');
                addSystemMessage(data.message);
                
                console.log('用户端拨号已自动取消');
            }
        });
        
        // 视频通话事件处理
        
        // 收到视频来电
        socket.on('video_call_incoming', function(data) {
            console.log('收到管理员视频来电，data类型:', typeof data, 'data键:', Object.keys(data));
            
            clearVideoCallTimeout(); // 清理超时定时器
            
            if (data.type === 'callback') {
                // 管理员回拨视频，需要用户接听
                console.log('管理员回拨视频，等待用户接听');
                currentVideoCallState = 'ringing';
                updateVideoCallButton('ringing');
                playRingtone();
                addSystemMessage('客服正在回拨您视频通话，请点击接听');
            } else if (data.offer) {
                // 管理员发送了视频WebRTC offer（用户接听了回拨）
                console.log('收到管理员的视频WebRTC offer');
                
                // 确保停止铃声和更新状态
                stopRingtone();
                currentVideoCallState = 'connecting';
                updateVideoCallButton('connecting');
                console.log('收到视频offer，停止铃声并更新状态为connecting');
                
                handleAdminVideoOffer(data.offer);
            } else {
                // 普通视频来电（从排队状态转为来电状态）
                console.log('轮到您了，管理员视频来电');
                currentVideoCallState = 'ringing';
                updateVideoCallButton('ringing');
                playRingtone();
                
                // 根据之前的状态给出不同提示
                if (currentVideoCallState === 'queued') {
                    addSystemMessage('🎉 轮到您了！客服正在呼叫您视频通话，请接听');
                } else {
                    addSystemMessage('客服正在呼叫您视频通话，请接听');
                }
            }
        });
        
        // 处理视频ICE候选
        socket.on('video_ice_candidate', function(data) {
            console.log('收到视频ICE候选:', data);
            if (videoPeerConnection && data.candidate && data.sender !== 'user') {
                // 检查是否已设置远程描述
                if (videoPeerConnection.remoteDescription) {
                    // 远程描述已设置，直接添加ICE候选
                    videoPeerConnection.addIceCandidate(new RTCIceCandidate(data.candidate))
                        .then(() => {
                            console.log('用户视频ICE候选添加成功');
                        })
                        .catch(error => {
                            console.error('用户视频ICE候选添加失败:', error);
                        });
                } else {
                    // 远程描述未设置，将ICE候选加入队列
                    console.log('视频远程描述未设置，ICE候选加入队列');
                    videoIceCandidateQueue.push(data.candidate);
                }
            }
        });
        
        // 视频通话被接听
        socket.on('video_call_accepted', function(data) {
            console.log('视频通话被接听:', data);
            startVideoCall();
        });
        
        // 视频通话被拒绝
        socket.on('video_call_rejected', function(data) {
            console.log('视频通话被拒绝:', data);
            clearVideoCallTimeout();
            cleanupVideoCall();
            currentVideoCallState = 'idle';
            updateVideoCallButton('idle');
            addSystemMessage('客服拒绝了视频通话');
        });
        
        // 视频通话被取消
        socket.on('video_call_cancelled', function(data) {
            console.log('视频通话被取消:', data);
            clearVideoCallTimeout();
            cleanupVideoCall();
            currentVideoCallState = 'idle';
            updateVideoCallButton('idle');
            addSystemMessage('视频通话已取消');
        });
        
        // 视频通话结束
        socket.on('video_call_ended', function(data) {
            console.log('视频通话结束:', data);
            cleanupVideoCall();
            currentVideoCallState = 'idle';
            updateVideoCallButton('idle');
            addSystemMessage('视频通话已结束');
        });
        
        // 视频通话排队状态更新
        socket.on('video_call_queue_update', function(data) {
            console.log('视频通话队列状态更新:', data);
            
            if (data.session_id === chatSessionId) {
                currentVideoCallState = 'queued';
                updateVideoCallButton('queued');
                
                // 显示排队信息
                addSystemMessage(data.message);
                
                // 如果是第1位，给出特殊提示
                if (data.position === 1) {
                    addSystemMessage('💡 您是下一位，客服处理完当前视频通话后将立即为您接通');
                }
            }
        });
        
        // 视频通话超时
        socket.on('video_call_timeout', function(data) {
            console.log('视频通话超时:', data);
            clearVideoCallTimeout();
            cleanupVideoCall();
            currentVideoCallState = 'idle';
            updateVideoCallButton('idle');
            addSystemMessage('视频通话超时，客服未接听');
        });
        
        // 管理员回拨视频被取消
        socket.on('video_call_callback_cancelled', function(data) {
            console.log('管理员取消了视频回拨:', data);
            
            if (data.session_id === chatSessionId) {
                // 停止铃声
                stopRingtone();
                
                // 重置状态
                currentVideoCallState = 'idle';
                updateVideoCallButton('idle');
                
                // 显示系统消息
                addSystemMessage('客服取消了视频回拨');
                
                console.log('用户端视频回拨状态已重置');
            }
        });
        
        // 视频通话自动取消（客服不在线）
        socket.on('video_call_auto_cancelled', function(data) {
            console.log('收到视频通话自动取消通知:', data);
            
            if (data.session_id === chatSessionId) {
                // 清理通话状态
                clearVideoCallTimeout();
                cleanupVideoCall();
                currentVideoCallState = 'idle';
                updateVideoCallButton('idle');
                
                // 显示系统消息
                addSystemMessage('📹 客服不在线，视频通话已自动取消');
                addSystemMessage(data.message);
                
                console.log('用户端视频通话已自动取消');
            }
        });
        
        // 桌面共享事件处理
        
        // 收到桌面共享接听确认
        socket.on('desktop_share_accepted', function(data) {
            console.log('桌面共享被接听:', data);
            
            // 检查是否已经在连接中或已连接，避免重复处理
            if (currentDesktopShareState === 'connected' || currentDesktopShareState === 'connecting') {
                console.log('桌面共享已在连接中或已连接，忽略重复的接听确认');
                return;
            }
            
            // 清理超时定时器
            clearDesktopShareTimeout();
            
            // 更新桌面共享状态
            currentDesktopShareState = 'connected';
            updateDesktopShareButton('connected');
            
            // 开始桌面共享
            startDesktopShare();
            
            addSystemMessage('🖥️ 桌面共享已连接');
        });
        
        // 桌面共享被拒绝
        socket.on('desktop_share_rejected', function(data) {
            console.log('桌面共享被拒绝:', data);
            
            // 清理超时定时器
            clearDesktopShareTimeout();
            
            // 清理桌面共享资源
            cleanupDesktopShare();
            
            // 重置桌面共享状态
            currentDesktopShareState = 'idle';
            updateDesktopShareButton('idle');
            
            addSystemMessage('🖥️ 桌面共享被拒绝');
        });
        
        // 桌面共享结束
        socket.on('desktop_share_ended', function(data) {
            console.log('桌面共享结束:', data);
            
            // 防止重复处理
            if (currentDesktopShareState === 'idle') {
                console.log('桌面共享状态已为空闲，跳过结束处理');
                return;
            }
            
            // 立即停止桌面共享计时器
            if (desktopShareTimer) {
                clearInterval(desktopShareTimer);
                desktopShareTimer = null;
            }
            
            // 清理桌面共享流
            if (desktopShareStream) {
                desktopShareStream.getTracks().forEach(track => track.stop());
                desktopShareStream = null;
            }
            
            // 关闭桌面共享WebRTC连接
            if (desktopSharePeerConnection) {
                desktopSharePeerConnection.close();
                desktopSharePeerConnection = null;
            }
            
            // 清空桌面共享ICE候选队列
            desktopShareIceCandidateQueue = [];
            
            // 重置状态
            isDesktopSharing = false;
            desktopShareStartTime = null;
            currentDesktopShareState = 'idle';
            updateDesktopShareButton('idle');
            
            addSystemMessage('🖥️ 桌面共享已结束');
        });
        
        // 桌面共享队列状态更新
        socket.on('desktop_share_queue_update', function(data) {
            console.log('桌面共享队列状态更新:', data);
            
            if (data.session_id === chatSessionId) {
                if (data.status === 'queued') {
                    currentDesktopShareState = 'queued';
                    updateDesktopShareButton('queued');
                    addSystemMessage(`🖥️ ${data.message}`);
                }
            }
        });
        
        // 桌面共享自动取消（管理员不在线）
        socket.on('desktop_share_auto_cancelled', function(data) {
            console.log('收到桌面共享自动取消通知:', data);
            
            if (data.session_id === chatSessionId) {
                // 清理桌面共享状态
                clearDesktopShareTimeout();
                cleanupDesktopShare();
                currentDesktopShareState = 'idle';
                updateDesktopShareButton('idle');
                
                // 显示系统消息
                addSystemMessage('🖥️ 客服不在线，桌面共享请求已自动取消');
                addSystemMessage(data.message);
                
                console.log('用户端桌面共享请求已自动取消');
            }
        });
        
        // 处理桌面共享ICE候选
        socket.on('desktop_share_ice_candidate', function(data) {
            console.log('收到桌面共享ICE候选:', data);
            if (desktopSharePeerConnection && data.candidate && data.sender !== 'user') {
                // 检查是否已设置远程描述
                if (desktopSharePeerConnection.remoteDescription) {
                    // 远程描述已设置，直接添加ICE候选
                    desktopSharePeerConnection.addIceCandidate(new RTCIceCandidate(data.candidate))
                        .then(() => {
                            console.log('用户桌面共享ICE候选添加成功');
                        })
                        .catch(error => {
                            console.error('用户桌面共享ICE候选添加失败:', error);
                        });
                } else {
                    // 远程描述未设置，将ICE候选加入队列
                    console.log('桌面共享远程描述未设置，ICE候选加入队列');
                    desktopShareIceCandidateQueue.push(data.candidate);
                }
            }
        });
        
        // 处理管理员桌面共享answer
        socket.on('admin_desktop_share_answer', function(data) {
            console.log('收到管理员桌面共享answer:', data);
            
            if (desktopSharePeerConnection && data.answer) {
                // 设置远程描述
                desktopSharePeerConnection.setRemoteDescription(new RTCSessionDescription(data.answer))
                    .then(() => {
                        console.log('桌面共享远程描述设置成功');
                        
                        // 处理队列中的ICE候选
                        while (desktopShareIceCandidateQueue.length > 0) {
                            const candidate = desktopShareIceCandidateQueue.shift();
                            desktopSharePeerConnection.addIceCandidate(new RTCIceCandidate(candidate))
                                .then(() => {
                                    console.log('队列中的桌面共享ICE候选添加成功');
                                })
                                .catch(error => {
                                    console.error('队列中的桌面共享ICE候选添加失败:', error);
                                });
                        }
                    })
                    .catch(error => {
                        console.error('设置桌面共享远程描述失败:', error);
                    });
            }
        });
        
        // 其他事件处理
    } catch (error) {
        console.error('初始化Socket失败:', error);
        updateConnectionStatus('error');
        addSystemMessage('初始化聊天失败，请刷新页面重试');
    }
}

// 加入聊天
function joinChat() {
    if (!socket || !socket.connected) {
        console.log('Socket未连接，无法加入聊天');
        return;
    }
    // 获取用户信息
    const nameInput = document.getElementById('userName');
    const phoneInput = document.getElementById('userPhone');
    
    // 只有当输入框有内容且与当前userInfo不同时才更新
    const newName = nameInput.value.trim();
    const newPhone = phoneInput.value.trim();
    
    if ((newName && newName !== userInfo.name) || (newPhone && newPhone !== userInfo.phone)) {
        userInfo.name = newName || userInfo.name;
        userInfo.phone = newPhone || userInfo.phone;
        saveToStorage();
        
        // 隐藏用户信息面板
        const userInfoPanel = document.getElementById('userInfoPanel');
        if (userInfoPanel) {
            userInfoPanel.style.display = 'none';
        }
    }
    
    socket.emit('join_chat', {
        session_id: chatSessionId,
        user_info: userInfo
    });
}

// 发送消息
function sendMessage() {

    // 获取用户信息
    const nameInput = document.getElementById('userName');
    const phoneInput = document.getElementById('userPhone');

    // 只有当输入框有内容且与当前userInfo不同时才更新
    const newName = nameInput.value.trim();
    const newPhone = phoneInput.value.trim();

    if ((newName && newName !== userInfo.name) || (newPhone && newPhone !== userInfo.phone)) {
        userInfo.name = newName || userInfo.name;
        userInfo.phone = newPhone || userInfo.phone;
        saveToStorage();

        // 隐藏用户信息面板
        const userInfoPanel = document.getElementById('userInfoPanel');
        if (userInfoPanel) {
            userInfoPanel.style.display = 'none';
        }
    }
    const input = document.getElementById('messageInput');
    const content = input.value.trim();
    
    if (!content) return;
    
    if (!socket || !socket.connected) {
        addSystemMessage('连接已断开，请刷新页面');
        return;
    }
    
    if (!chatSessionId) {
        addSystemMessage('会话未初始化，请稍后重试');
        return;
    }
    
    socket.emit('send_message', {
        session_id: chatSessionId,
        content: content,
        userName: newName,
        userPhone: newPhone
    });
    
    input.value = '';
}

// 添加消息到聊天区域
function addMessage(content, senderType, time) {
    const messagesDiv = document.getElementById('chatMessages');
    const messageDiv = document.createElement('div');
    
    const isUser = senderType === 'user';
    messageDiv.style.cssText = `
        margin-bottom: 20px;
        display: flex;
        flex-direction: column;
        ${isUser ? 'align-items: flex-end;' : 'align-items: flex-start;'}
    `;
    
    // 添加时间显示
    const timeDiv = document.createElement('div');
    timeDiv.style.cssText = `
        text-align: center;
        color: #999;
        font-size: 12px;
        margin-bottom: 10px;
        width: 100%;
    `;
    timeDiv.textContent = time || new Date().toLocaleTimeString();
    messageDiv.appendChild(timeDiv);
    
    // 消息气泡
    const bubbleDiv = document.createElement('div');
    bubbleDiv.style.cssText = `
        max-width: 80%;
        padding: 12px 16px;
        border-radius: 18px;
        position: relative;
        word-wrap: break-word;
        ${isUser ? 
            'background: #1E9FFF; color: white; border-bottom-right-radius: 6px;' :
            'background: white; color: #333; border: 1px solid #e0e0e0; border-bottom-left-radius: 6px;'
        }
    `;
    bubbleDiv.textContent = content;
    messageDiv.appendChild(bubbleDiv);
    
    messagesDiv.appendChild(messageDiv);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

// 添加系统消息
function addSystemMessage(content) {
    const messagesDiv = document.getElementById('chatMessages');
    const messageDiv = document.createElement('div');
    
    messageDiv.style.cssText = `
        margin-bottom: 10px;
        text-align: center;
    `;
    
    messageDiv.innerHTML = `
        <div style="
            display: inline-block;
            padding: 8px 16px;
            background: #f0f0f0;
            color: #666;
            border-radius: 12px;
            font-size: 12px;
            border: 1px solid #e0e0e0;
        ">${content}</div>
    `;
    
    messagesDiv.appendChild(messageDiv);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

// 显示正在输入指示器
function showTypingIndicator(sender, message) {
    // 移除现有的指示器
    hideTypingIndicator();
    
    const messagesDiv = document.getElementById('chatMessages');
    const typingDiv = document.createElement('div');
    typingDiv.id = 'typingIndicator';
    typingDiv.style.cssText = `
        margin-bottom: 10px;
        display: flex;
        justify-content: flex-start;
    `;
    
    typingDiv.innerHTML = `
        <div style="
            padding: 12px 16px;
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 18px;
            border-bottom-left-radius: 6px;
            font-style: italic;
            color: #666;
            font-size: 14px;
            max-width: 80%;
        ">${message}</div>
    `;
    
    messagesDiv.appendChild(typingDiv);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

// 隐藏正在输入指示器
function hideTypingIndicator() {
    const indicator = document.getElementById('typingIndicator');
    if (indicator) {
        indicator.remove();
    }
}

// 处理键盘事件
function handleKeyPress(event) {
    if (event.key === 'Enter') {
        sendMessage();
    }
}

// 切换表情面板
function toggleEmoji() {
    console.log('toggleEmoji 被调用');
    const emojiPanel = document.getElementById('emojiPanel');
    if (!emojiPanel) {
        console.error('找不到表情面板元素');
        return;
    }
    
    // 检查当前显示状态，如果为空字符串或none则显示，否则隐藏
    const currentDisplay = emojiPanel.style.display;
    const newDisplay = (currentDisplay === '' || currentDisplay === 'none') ? 'block' : 'none';
    emojiPanel.style.display = newDisplay;
    console.log('表情面板显示状态:', newDisplay);
}

// 插入表情
function insertEmoji(emoji) {
    console.log('insertEmoji 被调用，表情:', emoji);
    const messageInput = document.getElementById('messageInput');
    if (!messageInput) {
        console.error('找不到消息输入框');
        return;
    }
    
    const cursorPos = messageInput.selectionStart;
    const textBefore = messageInput.value.substring(0, cursorPos);
    const textAfter = messageInput.value.substring(cursorPos);
    
    messageInput.value = textBefore + emoji + textAfter;
    messageInput.focus();
    
    // 设置光标位置到表情后面
    const newCursorPos = cursorPos + emoji.length;
    messageInput.setSelectionRange(newCursorPos, newCursorPos);
    
    // 隐藏表情面板
    const emojiPanel = document.getElementById('emojiPanel');
    if (emojiPanel) {
        emojiPanel.style.display = 'none';
        console.log('表情面板已隐藏');
    }
    
    console.log('表情已插入到输入框');
}

// 上传图片
function uploadImage() {
    const imageInput = document.getElementById('imageInput');
    if (imageInput) {
        imageInput.click(); // 触发文件选择
    } else {
        console.error('找不到图片上传输入框');
    }
}

// 文件选择处理
document.getElementById('imageInput').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        // 检查文件类型
        if (!file.type.startsWith('image/')) {
            addSystemMessage('请选择图片文件');
            event.target.value = ''; // 清空选择
            return;
        }
        
        // 检查文件大小 (限制为5MB)
        const maxSize = 5 * 1024 * 1024; // 5MB
        if (file.size > maxSize) {
            addSystemMessage('图片文件过大，请选择小于5MB的图片');
            event.target.value = ''; // 清空选择
            return;
        }
        
        console.log('开始读取选择的图片文件:', file.name, '大小:', file.size);
        
        const reader = new FileReader();
        reader.onload = function(e) {
            const imageData = e.target.result;
            console.log('图片读取成功，发送图片消息');
            sendImageMessage(imageData);
            
            // 清空输入框，允许重复选择同一文件
            event.target.value = '';
        };
        
        reader.onerror = function(e) {
            console.error('图片读取失败:', e);
            addSystemMessage('图片读取失败，请重试');
            event.target.value = ''; // 清空选择
        };
        
        reader.readAsDataURL(file);
    }
});

// 上传文件
function uploadFile() {
    addSystemMessage('文件上传功能开发中...');
}

// 开始语音
function startVoice() {
    addSystemMessage('语音输入功能开发中...');
}

// 拨打电话
function makeCall() {
    const phoneInput = document.getElementById('phoneInput');
    const phoneNumber = phoneInput.value.trim();
    
    if (!phoneNumber) {
        addSystemMessage('请输入电话号码');
        return;
    }
    
    addSystemMessage(`正在为您转接电话 ${phoneNumber}...`);
}

// 播放提示音
function playMessageSound() {
    // 只有在用户已经与页面交互过才播放提示音
    if (!userHasInteracted) {
        console.log('用户尚未交互，跳过提示音播放');
        return;
    }
    
    try {
        // 创建AudioContext
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        
        // 如果AudioContext被暂停，恢复它
        if (audioContext.state === 'suspended') {
            audioContext.resume();
        }
        
        // 创建振荡器和增益节点
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        // 设置音频参数
        oscillator.type = 'sine';
        oscillator.frequency.setValueAtTime(800, audioContext.currentTime); // 800Hz，更悦耳的音调
        oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.1); // 0.1秒后降到600Hz
        
        // 设置音量渐变
        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.2, audioContext.currentTime + 0.01);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
        
        // 连接节点
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        // 播放音频
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.3);
        
        console.log('提示音已播放');
        
        // 清理资源
        oscillator.onended = function() {
            audioContext.close().catch(e => console.log('AudioContext已关闭'));
        };
        
    } catch (error) {
        console.error('播放提示音失败:', error);
    }
}

// 播放来电铃声
function playIncomingCallSound() {
    try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        if (audioContext.state === 'suspended') {
            audioContext.resume();
        }

        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();

        oscillator.type = 'sine';
        oscillator.frequency.setValueAtTime(1000, audioContext.currentTime); // 高音调
        oscillator.frequency.setValueAtTime(500, audioContext.currentTime + 0.5); // 0.5秒后降到500Hz

        gainNode.gain.setValueAtTime(0, audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.5, audioContext.currentTime + 0.01);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);

        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);

        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.3);

        oscillator.onended = function() {
            audioContext.close().catch(e => console.log('AudioContext已关闭'));
        };
    } catch (error) {
        console.error('播放来电铃声失败:', error);
    }
}

// 切换聊天窗口显示/隐藏
function toggleChat() {
    const chatWindow = document.getElementById('chatWindow');
    const userInfoPanel = document.getElementById('userInfoPanel');
    
    chatVisible = !chatVisible;
    
    if (chatVisible) {
        chatWindow.style.display = 'flex';
        
        // 检查是否有用户信息，如果没有才显示输入面板
        const hasUserInfo = userInfo.name && userInfo.name.trim() || userInfo.phone && userInfo.phone.trim();
        if (!hasUserInfo) {
            userInfoPanel.style.display = 'block';
        } else {
            userInfoPanel.style.display = 'none';
        }
        
        // 初始化Socket连接
        if (!socket) {
            initSocket();
        }
        
        // 聚焦到消息输入框
        setTimeout(() => {
            document.getElementById('messageInput').focus();
        }, 100);
    } else {
        chatWindow.style.display = 'none';
    }
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    restoreFromStorage();
    updateConnectionStatus('disconnected');
    
    // 确保表情面板默认隐藏
    const emojiPanel = document.getElementById('emojiPanel');
    if (emojiPanel) {
        emojiPanel.style.display = 'none';
    }
    
    // 添加用户交互检测
    const userInteractionEvents = ['click', 'touchstart', 'keydown', 'mousedown'];
    userInteractionEvents.forEach(eventType => {
        document.addEventListener(eventType, function() {
            if (!userHasInteracted) {
                userHasInteracted = true;
                console.log('用户已与页面交互，启用提示音功能');
            }
        }, { once: true }); // once: true 确保只触发一次
    });
    
    // 点击外部区域关闭表情面板
    document.addEventListener('click', function(e) {
        const emojiPanel = document.getElementById('emojiPanel');
        const emojiBtn = document.querySelector('button[onclick="toggleEmoji()"]');
        
        if (emojiPanel && emojiPanel.style.display === 'block') {
            if (!emojiPanel.contains(e.target) && !emojiBtn.contains(e.target)) {
                emojiPanel.style.display = 'none';
            }
        }
    });
});

// 处理图片粘贴
function handleImagePaste(event) {
    console.log('用户端粘贴事件触发:', event);
    
    // 处理不同类型的事件对象 - 优先尝试originalEvent
    let clipboardData = null;
    
    if (event.originalEvent && event.originalEvent.clipboardData) {
        clipboardData = event.originalEvent.clipboardData;
        console.log('使用originalEvent.clipboardData');
    } else if (event.clipboardData) {
        clipboardData = event.clipboardData;
        console.log('使用event.clipboardData');
    } else {
        console.log('没有找到clipboardData，忽略粘贴事件');
        return;
    }
    
    if (!clipboardData || !clipboardData.items) {
        console.log('clipboardData.items不存在，忽略粘贴事件');
        return;
    }
    
    const items = clipboardData.items;
    console.log('剪贴板项目数量:', items.length);
    
    for (let i = 0; i < items.length; i++) {
        const item = items[i];
        console.log('项目类型:', item.type);
        
        if (item.type.indexOf('image') !== -1) {
            console.log('检测到图片，阻止默认行为');
            event.preventDefault();
            
            const file = item.getAsFile();
            if (!file) {
                console.log('无法获取文件对象');
                continue;
            }
            
            console.log('开始读取图片文件，文件大小:', file.size);
            const reader = new FileReader();
            
            reader.onload = function(e) {
                const imageData = e.target.result;
                console.log('图片读取成功，数据长度:', imageData.length);
                sendImageMessage(imageData);
            };
            
            reader.onerror = function(e) {
                console.error('图片读取失败:', e);
                addSystemMessage('图片读取失败，请重试');
            };
            
            reader.readAsDataURL(file);
            break;
        }
    }
}

// 发送图片消息
function sendImageMessage(imageData) {
    if (!socket || !socket.connected) {
        addSystemMessage('连接已断开，请刷新页面');
        return;
    }
    
    if (!chatSessionId) {
        addSystemMessage('会话未初始化，请稍后重试');
        return;
    }
    
    // 获取用户信息
    const nameInput = document.getElementById('userName');
    const phoneInput = document.getElementById('userPhone');
    const newName = nameInput.value.trim();
    const newPhone = phoneInput.value.trim();

    // 更新用户信息
    if ((newName && newName !== userInfo.name) || (newPhone && newPhone !== userInfo.phone)) {
        userInfo.name = newName || userInfo.name;
        userInfo.phone = newPhone || userInfo.phone;
        saveToStorage();

        // 隐藏用户信息面板
        const userInfoPanel = document.getElementById('userInfoPanel');
        if (userInfoPanel) {
            userInfoPanel.style.display = 'none';
        }
    }
    
    socket.emit('send_message', {
        session_id: chatSessionId,
        content: '[图片]',
        message_type: 'image',
        image_data: imageData,
        userName: newName,
        userPhone: newPhone
    });
}

// 添加图片消息到聊天区域
function addImageMessage(imageData, senderType, time) {
    const messagesDiv = document.getElementById('chatMessages');
    const messageDiv = document.createElement('div');
    
    const isUser = senderType === 'user';
    messageDiv.style.cssText = `
        margin-bottom: 20px;
        display: flex;
        flex-direction: column;
        ${isUser ? 'align-items: flex-end;' : 'align-items: flex-start;'}
    `;
    
    // 添加时间显示
    const timeDiv = document.createElement('div');
    timeDiv.style.cssText = `
        text-align: center;
        color: #999;
        font-size: 12px;
        margin-bottom: 10px;
        width: 100%;
    `;
    timeDiv.textContent = time || new Date().toLocaleTimeString();
    messageDiv.appendChild(timeDiv);
    
    // 图片气泡
    const bubbleDiv = document.createElement('div');
    bubbleDiv.style.cssText = `
        max-width: 80%;
        padding: 8px;
        border-radius: 18px;
        position: relative;
        ${isUser ? 
            'background: #1E9FFF; border-bottom-right-radius: 6px;' :
            'background: white; border: 1px solid #e0e0e0; border-bottom-left-radius: 6px;'
        }
    `;
    
    const img = document.createElement('img');
    img.src = imageData;
    img.style.cssText = `
        max-width: 100%;
        max-height: 200px;
        border-radius: 8px;
        cursor: pointer;
        transition: transform 0.2s;
    `;
    
    // 点击图片显示大图
    img.onclick = function() {
        showImageModal(imageData);
    };
    
    // 鼠标悬浮效果
    img.onmouseover = function() {
        this.style.transform = 'scale(1.05)';
    };
    
    img.onmouseout = function() {
        this.style.transform = 'scale(1)';
    };
    
    bubbleDiv.appendChild(img);
    messageDiv.appendChild(bubbleDiv);
    
    messagesDiv.appendChild(messageDiv);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

// 显示图片模态框
function showImageModal(imageData) {
    // 创建模态框
    const modal = document.createElement('div');
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10000;
        cursor: pointer;
    `;
    
    const img = document.createElement('img');
    img.src = imageData;
    img.style.cssText = `
        max-width: 90%;
        max-height: 90%;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    `;
    
    modal.appendChild(img);
    document.body.appendChild(modal);
    
    // 点击模态框关闭
    modal.onclick = function() {
        document.body.removeChild(modal);
    };
    
    // ESC键关闭
    const escHandler = function(event) {
        if (event.key === 'Escape') {
            document.body.removeChild(modal);
            document.removeEventListener('keydown', escHandler);
        }
    };
    document.addEventListener('keydown', escHandler);
}

// 添加粘贴事件监听器
document.getElementById('messageInput').addEventListener('paste', handleImagePaste);

// 只在页面真正关闭时断开连接（不包括切换标签、最小化等）
window.addEventListener('beforeunload', function(event) {
    // 只在真正关闭标签页时断开连接
    if (socket && socket.connected && chatSessionId) {
        console.log('页面关闭，主动断开会话并断开WebSocket连接');
        
        // 发送断开会话消息
        socket.emit('user_disconnect_session', {
            session_id: chatSessionId
        });
        
        // 等待一小段时间确保消息发送完成
        setTimeout(function() {
            socket.disconnect();
        }, 100);
    } else if (socket && socket.connected) {
        console.log('页面关闭，断开WebSocket连接（无活跃会话）');
        socket.disconnect();
    }
});

// 移除visibilitychange事件处理，避免在切换标签时断开连接
// 如果需要在页面不可见时暂停某些功能，可以在这里添加
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        console.log('页面隐藏，但保持WebSocket连接');
        // 页面隐藏时可以暂停一些非关键操作，但保持连接
    } else {
        console.log('页面重新可见，WebSocket连接保持活跃');
        // 页面重新可见时可以恢复操作
    }
});

// 处理管理员的offer
async function handleAdminOffer(offer) {
    try {
        console.log('处理管理员的offer');
        
        // 初始化远程音频元素
        initRemoteAudio();
        
        // 创建WebRTC连接
        peerConnection = new RTCPeerConnection(rtcConfig);
        
        // 获取用户麦克风
        localStream = await navigator.mediaDevices.getUserMedia({
            audio: {
                echoCancellation: true,
                noiseSuppression: true,
                autoGainControl: true
            },
            video: false
        });
        
        // 添加本地音频流
        localStream.getTracks().forEach(track => {
            peerConnection.addTrack(track, localStream);
            console.log('用户音频轨道已添加到连接');
        });
        
        // 处理远程音频流
        peerConnection.ontrack = function(event) {
            console.log('收到管理员音频流');
            if (remoteAudio && event.streams[0]) {
                remoteAudio.srcObject = event.streams[0];
                console.log('管理员音频流已设置到播放元素');
            }
        };
        
        // 处理ICE候选
        peerConnection.onicecandidate = function(event) {
            if (event.candidate) {
                console.log('发送用户ICE候选');
                socket.emit('ice_candidate', {
                    session_id: chatSessionId,
                    candidate: event.candidate,
                    sender: 'user'
                });
            }
        };
        
        // 连接状态变化
        peerConnection.onconnectionstatechange = function() {
            console.log('用户WebRTC连接状态:', peerConnection.connectionState);
            if (peerConnection.connectionState === 'connected') {
                console.log('用户语音通话已建立');
                updateCallButton('connected');
                addSystemMessage('语音通话已连接');
                startCall();
            } else if (peerConnection.connectionState === 'disconnected' || 
                      peerConnection.connectionState === 'failed') {
                console.log('用户语音通话连接断开');
                cleanupCall();
            }
        };
        
        // 设置远程描述
        await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
        
        // 处理队列中的ICE候选
        console.log('处理队列中的ICE候选，队列长度:', iceCandidateQueue.length);
        while (iceCandidateQueue.length > 0) {
            const candidate = iceCandidateQueue.shift();
            peerConnection.addIceCandidate(new RTCIceCandidate(candidate))
                .then(() => {
                    console.log('队列中的用户ICE候选添加成功');
                })
                .catch(error => {
                    console.error('队列中的用户ICE候选添加失败:', error);
                });
        }
        
        // 创建应答
        const answer = await peerConnection.createAnswer();
        console.log('用户创建应答成功:', answer);
        
        await peerConnection.setLocalDescription(answer);
        console.log('用户设置本地描述成功');
        
        // 发送应答给管理员
        socket.emit('voice_call_answer', {
            session_id: chatSessionId,
            answer: answer
        });
        
        console.log('用户应答已发送，answer类型:', answer?.type);
        
    } catch (error) {
        console.error('处理管理员offer失败:', error);
        addSystemMessage('建立通话连接失败: ' + error.message);
        cleanupCall();
    }
}

// 处理通话超时
function handleCallTimeout() {
    console.log('处理通话超时');
    
    // 清理超时定时器
    if (callTimeoutTimer) {
        clearTimeout(callTimeoutTimer);
        callTimeoutTimer = null;
    }
    
    // 发送超时通知给服务器
    if (socket && socket.connected && chatSessionId) {
        socket.emit('voice_call_timeout', {
            session_id: chatSessionId,
            user_info: {
                name: localStorage.getItem('userName') || '',
                phone: localStorage.getItem('userPhone') || ''
            }
        });
    }
    
    // 重置状态
    currentCallState = 'idle';
    updateCallButton('idle');
    addSystemMessage('客服暂时无法接听，已为您留下呼叫记录');
}

// 清理通话超时定时器
function clearCallTimeout() {
    if (callTimeoutTimer) {
        clearTimeout(callTimeoutTimer);
        callTimeoutTimer = null;
        console.log('通话超时定时器已清理');
    }
}

// 拒绝语音通话
function rejectVoiceCall() {
    console.log('拒绝语音通话');
    
    if (!socket || !socket.connected || !chatSessionId) {
        console.log('无效的连接状态，无法拒绝通话');
        return;
    }
    
    // 停止铃声
    stopRingtone();
    
    // 发送拒绝通话信号
    socket.emit('voice_call_reject', {
        session_id: chatSessionId,
        user_info: {
            name: localStorage.getItem('userName') || '',
            phone: localStorage.getItem('userPhone') || ''
        }
    });
    
    // 添加系统消息
    addSystemMessage('您已拒绝语音通话');
    
    currentCallState = 'idle';
    updateCallButton('idle');
    
    console.log('用户拒绝语音通话');
}

// 铃声相关变量
let userAudioContext = null;
let userRingtone = null;

// 初始化用户音频系统
function initUserAudio() {
    try {
        userAudioContext = new (window.AudioContext || window.webkitAudioContext)();
        console.log('用户音频系统初始化成功');
    } catch (error) {
        console.error('用户音频系统初始化失败:', error);
    }
}

// 播放持续铃声
function playRingtone() {
    if (!userAudioContext) {
        initUserAudio();
    }
    
    if (!userAudioContext) {
        console.warn('音频系统不可用，无法播放铃声');
        return;
    }
    
    try {
        // 停止之前的铃声
        stopRingtone();
        
        // 创建铃声 - 使用双音调
        const oscillator1 = userAudioContext.createOscillator();
        const oscillator2 = userAudioContext.createOscillator();
        const gainNode = userAudioContext.createGain();
        
        // 设置音调频率
        oscillator1.frequency.setValueAtTime(1000, userAudioContext.currentTime); // 高音
        oscillator2.frequency.setValueAtTime(800, userAudioContext.currentTime); // 低音
        
        // 设置音量
        gainNode.gain.setValueAtTime(0.4, userAudioContext.currentTime);
        
        // 连接音频节点
        oscillator1.connect(gainNode);
        oscillator2.connect(gainNode);
        gainNode.connect(userAudioContext.destination);
        
        // 启动铃声
        oscillator1.start();
        oscillator2.start();
        
        // 保存引用以便停止
        userRingtone = {
            oscillator1: oscillator1,
            oscillator2: oscillator2,
            gainNode: gainNode
        };
        
        // 创建铃声模式 - 响铃1秒，停止0.5秒，循环
        setTimeout(() => {
            stopRingtone();
            // 如果还在来电状态，继续播放铃声
            if (currentCallState === 'ringing') {
                setTimeout(() => {
                    if (currentCallState === 'ringing') {
                        playRingtone();
                    }
                }, 500); // 停止0.5秒后继续
            }
        }, 1000); // 播放1秒
        
        console.log('用户铃声开始播放');
    } catch (error) {
        console.error('播放用户铃声失败:', error);
    }
}

// 停止铃声
function stopRingtone() {
    if (userRingtone) {
        try {
            userRingtone.oscillator1.stop();
            userRingtone.oscillator2.stop();
            userRingtone = null;
            console.log('用户铃声已停止');
        } catch (error) {
            console.error('停止用户铃声失败:', error);
            userRingtone = null;
        }
    }
}

// 播放短促提示音
function playNewMessageSound() {
    try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.type = 'sine';
        oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
        gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.2);
        
        oscillator.onended = function() {
            audioContext.close().catch(e => console.log('AudioContext已关闭'));
        };
    } catch (error) {
        console.error('播放提示音失败:', error);
    }
}

// 初始化WebSocket连接
initializeSocket();

// 初始化用户音频系统（需要用户交互）
document.addEventListener('click', function initAudioOnFirstClick() {
    initUserAudio();
    document.removeEventListener('click', initAudioOnFirstClick);
}, { once: true });

// 发起视频通话
function initiateVideoCall() {
    console.log('发起视频通话');
    
    if (!socket || !socket.connected) {
        addSystemMessage('连接已断开，无法发起视频通话');
        return;
    }
    
    if (!chatSessionId) {
        addSystemMessage('会话未建立，无法发起视频通话');
        return;
    }
    
    isVideoCall = true;
    currentVideoCallState = 'calling';
    updateVideoCallButton('calling');
    
    // 发送视频通话请求
    socket.emit('video_call_request', {
        session_id: chatSessionId,
        user_info: {
            name: localStorage.getItem('userName') || '',
            phone: localStorage.getItem('userPhone') || ''
        }
    });
    
    addSystemMessage('正在呼叫客服视频通话，请稍候...');
    
    // 设置30秒超时
    videoCallTimeoutTimer = setTimeout(() => {
        if (currentVideoCallState === 'calling') {
            console.log('视频通话超时，无人接听');
            handleVideoCallTimeout();
        }
    }, 30000); // 30秒超时
}

// 取消视频通话
function cancelVideoCall() {
    console.log('取消视频通话');
    
    if (!socket || !socket.connected || !chatSessionId) {
        console.log('无效的连接状态，无法取消视频通话');
        return;
    }
    
    // 清理状态
    clearVideoCallTimeout();
    cleanupVideoCall();
    
    // 发送取消视频通话信号
    socket.emit('video_call_cancel', {
        session_id: chatSessionId,
        user_info: {
            name: localStorage.getItem('userName') || '',
            phone: localStorage.getItem('userPhone') || ''
        }
    });
    
    // 添加系统消息到用户端聊天框
    addSystemMessage('您已取消视频通话');
    
    currentVideoCallState = 'idle';
    updateVideoCallButton('idle');
}

// 结束视频通话
function endVideoCall() {
    console.log('用户端开始结束视频通话');
    
    if (socket && socket.connected) {
        console.log('发送video_call_end事件到服务器，会话ID:', chatSessionId);
        socket.emit('video_call_end', {
            session_id: chatSessionId
        });
        console.log('video_call_end事件已发送');
    } else {
        console.log('Socket未连接，无法发送video_call_end事件');
    }
    
    cleanupVideoCall();
    updateVideoCallButton('idle');
    
    if (videoCallStartTime) {
        const duration = Math.floor((Date.now() - videoCallStartTime) / 1000);
        const minutes = Math.floor(duration / 60);
        const seconds = duration % 60;
        addSystemMessage(`视频通话已结束，通话时长: ${minutes}:${seconds.toString().padStart(2, '0')}`);
    } else {
        addSystemMessage('视频通话已结束');
    }
    
    console.log('用户端视频通话结束处理完成');
}

// 接听视频通话
async function answerVideoCall() {
    console.log('接听视频通话');
    
    try {
        // 立即停止铃声
        stopRingtone();
        console.log('用户接听视频通话，停止铃声');
        
        // 更新通话状态为已接听
        currentVideoCallState = 'connecting';
        updateVideoCallButton('connecting');
        
        // 发送接听确认（让管理员创建WebRTC连接）
        socket.emit('video_call_accept', {
            session_id: chatSessionId,
            user_info: {
                name: localStorage.getItem('userName') || '',
                phone: localStorage.getItem('userPhone') || ''
            }
        });
        
        addSystemMessage('已接听视频通话，等待建立视频连接...');
        
    } catch (error) {
        console.error('接听视频通话失败:', error);
        addSystemMessage('接听视频通话失败');
        updateVideoCallButton('idle');
    }
}

// 开始视频通话
function startVideoCall() {
    isVideoCallActive = true;
    videoCallStartTime = Date.now();
    currentVideoCallState = 'connected';
    updateVideoCallButton('connected');
    
    // 开始计时
    videoCallTimer = setInterval(() => {
        if (videoCallStartTime) {
            const duration = Math.floor((Date.now() - videoCallStartTime) / 1000);
            const minutes = Math.floor(duration / 60);
            const seconds = duration % 60;
            updateVideoCallButton('connected', `${minutes}:${seconds.toString().padStart(2, '0')}`);
        }
    }, 1000);
    
    addSystemMessage('视频通话已连接');
}

// 清理视频通话资源
function cleanupVideoCall() {
    isVideoCallActive = false;
    videoCallStartTime = null;
    
    if (videoCallTimer) {
        clearInterval(videoCallTimer);
        videoCallTimer = null;
    }
    
    if (videoLocalStream) {
        videoLocalStream.getTracks().forEach(track => track.stop());
        videoLocalStream = null;
    }
    
    if (videoRemoteStream) {
        videoRemoteStream = null;
    }
    
    // 清理远程视频
    if (remoteVideo) {
        remoteVideo.srcObject = null;
        remoteVideo.remove(); // 从DOM中移除
        remoteVideo = null;
        console.log('用户远程视频已清理');
    }
    
    // 清理本地视频
    if (localVideo) {
        localVideo.srcObject = null;
        localVideo.remove(); // 从DOM中移除
        localVideo = null;
        console.log('用户本地视频已清理');
    }
    
    if (videoPeerConnection) {
        videoPeerConnection.close();
        videoPeerConnection = null;
    }
    
    // 清空视频ICE候选队列
    videoIceCandidateQueue = [];
    console.log('用户视频ICE候选队列已清空');
    
    console.log('用户视频通话资源清理完成');
}

// 清理视频通话超时
function clearVideoCallTimeout() {
    if (videoCallTimeoutTimer) {
        clearTimeout(videoCallTimeoutTimer);
        videoCallTimeoutTimer = null;
    }
}

// 处理视频通话超时
function handleVideoCallTimeout() {
    console.log('视频通话超时处理');
    
    if (!socket || !socket.connected || !chatSessionId) {
        console.log('无效的连接状态，无法处理视频通话超时');
        return;
    }
    
    // 清理状态
    clearVideoCallTimeout();
    cleanupVideoCall();
    
    // 发送超时信号
    socket.emit('video_call_timeout', {
        session_id: chatSessionId,
        user_info: {
            name: localStorage.getItem('userName') || '',
            phone: localStorage.getItem('userPhone') || ''
        }
    });
    
    // 添加系统消息
    addSystemMessage('视频通话超时，客服未接听');
    
    currentVideoCallState = 'idle';
    updateVideoCallButton('idle');
}

// 桌面共享按钮状态更新
function updateDesktopShareButton(state, text) {
    const desktopShareBtn = document.getElementById('desktopShareBtn');
    const desktopShareBtnText = document.getElementById('desktopShareBtnText');
    
    if (!desktopShareBtn || !desktopShareBtnText) return;
    
    switch (state) {
        case 'idle':
            desktopShareBtn.style.background = 'none';
            desktopShareBtn.style.borderColor = 'rgba(255,255,255,0.3)';
            desktopShareBtnText.textContent = '桌面共享';
            desktopShareBtn.onclick = initiateDesktopShare;
            break;
        case 'calling':
            desktopShareBtn.style.background = 'rgba(255,193,7,0.8)';
            desktopShareBtn.style.borderColor = '#ffc107';
            desktopShareBtnText.textContent = '请求中...';
            desktopShareBtn.onclick = cancelDesktopShare;
            break;
        case 'connected':
            desktopShareBtn.style.background = 'rgba(220,53,69,0.8)';
            desktopShareBtn.style.borderColor = '#dc3545';
            desktopShareBtnText.textContent = text || '停止共享';
            desktopShareBtn.onclick = endDesktopShare;
            break;
        case 'connecting':
            desktopShareBtn.style.background = 'rgba(32,201,151,0.8)';
            desktopShareBtn.style.borderColor = '#20c997';
            desktopShareBtnText.textContent = '连接中...';
            desktopShareBtn.onclick = endDesktopShare;
            break;
        case 'queued':
            desktopShareBtn.style.background = 'rgba(255,193,7,0.8)';
            desktopShareBtn.style.borderColor = '#ffc107';
            desktopShareBtnText.textContent = '排队中...';
            desktopShareBtn.onclick = cancelDesktopShare;
            break;
    }
}

// 发起桌面共享
function initiateDesktopShare() {
    console.log('发起桌面共享');
    
    if (!socket || !socket.connected) {
        addSystemMessage('连接已断开，无法发起桌面共享');
        return;
    }
    
    if (!chatSessionId) {
        addSystemMessage('会话未建立，无法发起桌面共享');
        return;
    }
    
    currentDesktopShareState = 'calling';
    updateDesktopShareButton('calling');
    
    // 发送桌面共享请求
    socket.emit('desktop_share_request', {
        session_id: chatSessionId,
        user_info: {
            name: localStorage.getItem('userName') || '',
            phone: localStorage.getItem('userPhone') || ''
        }
    });
    
    addSystemMessage('正在请求桌面共享，请稍候...');
    
    // 设置30秒超时
    desktopShareTimeoutTimer = setTimeout(() => {
        if (currentDesktopShareState === 'calling') {
            console.log('桌面共享请求超时，无人接听');
            handleDesktopShareTimeout();
        }
    }, 30000); // 30秒超时
}

// 取消桌面共享
function cancelDesktopShare() {
    console.log('取消桌面共享');
    
    if (!socket || !socket.connected || !chatSessionId) {
        console.log('无效的连接状态，无法取消桌面共享');
        return;
    }
    
    // 清理状态
    clearDesktopShareTimeout();
    cleanupDesktopShare();
    
    // 发送取消桌面共享信号
    socket.emit('desktop_share_cancel', {
        session_id: chatSessionId
    });
    
    addSystemMessage('您已取消桌面共享请求');
    
    currentDesktopShareState = 'idle';
    updateDesktopShareButton('idle');
}

// 结束桌面共享
function endDesktopShare() {
    console.log('结束桌面共享');
    
    // 防止重复发送事件
    if (currentDesktopShareState === 'idle') {
        console.log('桌面共享状态已为空闲，跳过结束事件');
        return;
    }
    
    // 先清理资源
    cleanupDesktopShare();
    
    // 然后发送结束事件
    if (socket && socket.connected) {
        socket.emit('desktop_share_end', {
            session_id: chatSessionId
        });
    }
    
    // 重置状态
    currentDesktopShareState = 'idle';
    updateDesktopShareButton('idle');
    
    if (desktopShareStartTime) {
        const duration = Math.floor((Date.now() - desktopShareStartTime) / 1000);
        const minutes = Math.floor(duration / 60);
        const seconds = duration % 60;
        addSystemMessage(`桌面共享已结束，共享时长: ${minutes}:${seconds.toString().padStart(2, '0')}`);
    } else {
        addSystemMessage('桌面共享已结束');
    }
}

// 开始桌面共享
async function startDesktopShare() {
    try {
        console.log('开始桌面共享');
        
        // 检查是否已经在共享中，避免重复发送offer
        if (isDesktopSharing || desktopSharePeerConnection) {
            console.log('桌面共享已在连接中，忽略重复的startDesktopShare调用');
            return;
        }
        
        // 创建桌面共享WebRTC连接
        await createDesktopSharePeerConnection();
        
        // 创建offer
        const offer = await desktopSharePeerConnection.createOffer();
        await desktopSharePeerConnection.setLocalDescription(offer);
        
        // 发送offer给管理员
        socket.emit('desktop_share_offer', {
            session_id: chatSessionId,
            offer: offer,
            user_info: {
                name: localStorage.getItem('userName') || '',
                phone: localStorage.getItem('userPhone') || ''
            }
        });
        
        isDesktopSharing = true;
        desktopShareStartTime = Date.now();
        currentDesktopShareState = 'connected';
        updateDesktopShareButton('connected');
        
        // 开始计时
        desktopShareTimer = setInterval(() => {
            if (desktopShareStartTime) {
                const duration = Math.floor((Date.now() - desktopShareStartTime) / 1000);
                const minutes = Math.floor(duration / 60);
                const seconds = duration % 60;
                updateDesktopShareButton('connected', `${minutes}:${seconds.toString().padStart(2, '0')}`);
            }
        }, 1000);
        
        addSystemMessage('桌面共享已连接');
        
    } catch (error) {
        console.error('开始桌面共享失败:', error);
        cleanupDesktopShare();
        currentDesktopShareState = 'idle';
        updateDesktopShareButton('idle');
        addSystemMessage('桌面共享连接失败');
    }
}

// 清理桌面共享资源
function cleanupDesktopShare() {
    console.log('开始清理桌面共享资源');
    
    // 防止重复清理
    if (currentDesktopShareState === 'idle') {
        console.log('桌面共享状态已为空闲，跳过清理');
        return;
    }
    
    isDesktopSharing = false;
    desktopShareStartTime = null;
    
    if (desktopShareTimer) {
        clearInterval(desktopShareTimer);
        desktopShareTimer = null;
    }
    
    if (desktopShareStream) {
        desktopShareStream.getTracks().forEach(track => track.stop());
        desktopShareStream = null;
    }
    
    if (desktopSharePeerConnection) {
        desktopSharePeerConnection.close();
        desktopSharePeerConnection = null;
    }
    
    // 清空桌面共享ICE候选队列
    desktopShareIceCandidateQueue = [];
    console.log('桌面共享资源清理完成');
}

// 清除桌面共享超时
function clearDesktopShareTimeout() {
    if (desktopShareTimeoutTimer) {
        clearTimeout(desktopShareTimeoutTimer);
        desktopShareTimeoutTimer = null;
    }
}

// 处理桌面共享超时
function handleDesktopShareTimeout() {
    console.log('桌面共享请求超时');
    currentDesktopShareState = 'idle';
    updateDesktopShareButton('idle');
    addSystemMessage('桌面共享请求超时，无人接听');
}

// 获取用户桌面共享
async function getUserDesktopShare() {
    try {
        console.log('正在获取用户桌面共享权限...');
        
        desktopShareStream = await navigator.mediaDevices.getDisplayMedia({
            video: {
                width: { ideal: 1920 },
                height: { ideal: 1080 },
                frameRate: { ideal: 30 }
            },
            audio: false // 桌面共享通常不需要音频
        });
        
        console.log('桌面共享权限获取成功');
        return desktopShareStream;
    } catch (error) {
        console.error('获取桌面共享失败:', error);
        throw error;
    }
}

// 创建桌面共享WebRTC连接
async function createDesktopSharePeerConnection() {
    try {
        console.log('创建桌面共享WebRTC连接...');
        
        desktopSharePeerConnection = new RTCPeerConnection(rtcConfig);
        
        // 添加本地桌面共享流
        const stream = await getUserDesktopShare();
        stream.getTracks().forEach(track => {
            desktopSharePeerConnection.addTrack(track, stream);
            console.log('桌面共享轨道已添加到连接:', track.kind);
        });
        
        // 处理远程桌面共享流
        desktopSharePeerConnection.ontrack = function(event) {
            console.log('收到远程桌面共享流');
            if (event.streams && event.streams[0]) {
                // 这里可以处理远程桌面共享流，如果需要的话
                console.log('远程桌面共享流已接收');
            }
        };
        
        // 处理ICE候选
        desktopSharePeerConnection.onicecandidate = function(event) {
            if (event.candidate) {
                console.log('发送桌面共享ICE候选');
                socket.emit('desktop_share_ice_candidate', {
                    session_id: chatSessionId,
                    candidate: event.candidate,
                    sender: 'user'
                });
            }
        };
        
        // 连接状态变化
        desktopSharePeerConnection.onconnectionstatechange = function() {
            console.log('桌面共享WebRTC连接状态:', desktopSharePeerConnection.connectionState);
            if (desktopSharePeerConnection.connectionState === 'connected') {
                console.log('桌面共享已建立');
                startDesktopShare();
            } else if (desktopSharePeerConnection.connectionState === 'disconnected' || 
                      desktopSharePeerConnection.connectionState === 'failed') {
                console.log('桌面共享连接断开');
                cleanupDesktopShare();
            }
        };
        
        return desktopSharePeerConnection;
    } catch (error) {
        console.error('创建桌面共享WebRTC连接失败:', error);
        throw error;
    }
}

// 处理桌面共享ICE候选
socket.on('desktop_share_ice_candidate', function(data) {
    console.log('收到桌面共享ICE候选:', data);
    if (desktopSharePeerConnection && data.candidate && data.sender !== 'user') {
        // 检查是否已设置远程描述
        if (desktopSharePeerConnection.remoteDescription) {
            // 远程描述已设置，直接添加ICE候选
            desktopSharePeerConnection.addIceCandidate(new RTCIceCandidate(data.candidate))
                .then(() => {
                    console.log('用户桌面共享ICE候选添加成功');
                })
                .catch(error => {
                    console.error('用户桌面共享ICE候选添加失败:', error);
                });
        } else {
            // 远程描述未设置，将ICE候选加入队列
            console.log('桌面共享远程描述未设置，ICE候选加入队列');
            desktopShareIceCandidateQueue.push(data.candidate);
        }
    }
});

// 处理管理员桌面共享answer
socket.on('admin_desktop_share_answer', function(data) {
    console.log('收到管理员桌面共享answer:', data);
    
    if (desktopSharePeerConnection && data.answer) {
        // 设置远程描述
        desktopSharePeerConnection.setRemoteDescription(new RTCSessionDescription(data.answer))
            .then(() => {
                console.log('桌面共享远程描述设置成功');
                
                // 处理队列中的ICE候选
                while (desktopShareIceCandidateQueue.length > 0) {
                    const candidate = desktopShareIceCandidateQueue.shift();
                    desktopSharePeerConnection.addIceCandidate(new RTCIceCandidate(candidate))
                        .then(() => {
                            console.log('队列中的桌面共享ICE候选添加成功');
                        })
                        .catch(error => {
                            console.error('队列中的桌面共享ICE候选添加失败:', error);
                        });
                }
            })
            .catch(error => {
                console.error('设置桌面共享远程描述失败:', error);
            });
    }
});

// 其他事件处理
</script>